/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.sys.modular.scorerecords.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.core.util.PoiUtil;
import vip.xiaonuo.sys.modular.courseselection.entity.CourseSelection;
import vip.xiaonuo.sys.modular.courseselection.service.CourseSelectionService;
import vip.xiaonuo.sys.modular.scoreitem.entity.ScoreItem;
import vip.xiaonuo.sys.modular.scoreitem.service.ScoreItemService;
import vip.xiaonuo.sys.modular.scorerecords.entity.ScoreRecords;
import vip.xiaonuo.sys.modular.scorerecords.enums.ScoreRecordsExceptionEnum;
import vip.xiaonuo.sys.modular.scorerecords.mapper.ScoreRecordsMapper;
import vip.xiaonuo.sys.modular.scorerecords.param.ScoreRecordsParam;
import vip.xiaonuo.sys.modular.scorerecords.service.ScoreRecordsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 打分记录service接口实现类
 *
 * @author kongxm
 * @date 2022-07-17 14:52:27
 */
@Service
public class ScoreRecordsServiceImpl extends ServiceImpl<ScoreRecordsMapper, ScoreRecords> implements ScoreRecordsService {
    @Autowired
    private CourseSelectionService courseSelectionService;
    @Autowired
    private ScoreItemService scoreItemService;

    @Override
    public PageResult<ScoreRecords> page(ScoreRecordsParam scoreRecordsParam) {
        QueryWrapper<ScoreRecords> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(scoreRecordsParam)) {

            // 根据排课id 查询
            if (ObjectUtil.isNotEmpty(scoreRecordsParam.getCourseScheduleId())) {
                queryWrapper.lambda().eq(ScoreRecords::getCourseScheduleId, scoreRecordsParam.getCourseScheduleId());
            }
            // 根据选课id 查询
            if (ObjectUtil.isNotEmpty(scoreRecordsParam.getCourseSelectionId())) {
                queryWrapper.lambda().eq(ScoreRecords::getCourseSelectionId, scoreRecordsParam.getCourseSelectionId());
            }
            // 根据打分项 查询
            if (ObjectUtil.isNotEmpty(scoreRecordsParam.getItemId())) {
                queryWrapper.lambda().eq(ScoreRecords::getItemId, scoreRecordsParam.getItemId());
            }
            // 根据项目得分 查询
            if (ObjectUtil.isNotEmpty(scoreRecordsParam.getItemScore())) {
                queryWrapper.lambda().eq(ScoreRecords::getItemScore, scoreRecordsParam.getItemScore());
            }
            // 根据0-项目打分项 1-答辩打分项 查询
            if (ObjectUtil.isNotEmpty(scoreRecordsParam.getCategory())) {
                queryWrapper.lambda().eq(ScoreRecords::getCategory, scoreRecordsParam.getCategory());
            }
        }
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<ScoreRecords> list(ScoreRecordsParam scoreRecordsParam) {
        LambdaQueryWrapper<ScoreRecords> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ScoreRecords::getStatus, 0);
        if (scoreRecordsParam.getCourseSelectionId() != null) {
            queryWrapper.eq(ScoreRecords::getCourseSelectionId, scoreRecordsParam.getCourseSelectionId());
        }
        if (scoreRecordsParam.getCourseScheduleFrequencyId() != null) {
            queryWrapper.eq(ScoreRecords::getCourseScheduleFrequencyId, scoreRecordsParam.getCourseScheduleFrequencyId());
        }

        if (scoreRecordsParam.getCategory() != null) {
            queryWrapper.eq(ScoreRecords::getCategory, scoreRecordsParam.getCategory());
        }
        return this.list(queryWrapper);
    }

    @Override
    public void add(ScoreRecordsParam scoreRecordsParam) {
        ScoreRecords scoreRecords = new ScoreRecords();
        BeanUtil.copyProperties(scoreRecordsParam, scoreRecords);
        this.save(scoreRecords);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(List<ScoreRecordsParam> scoreRecordsParamList) {
        assert CollectionUtil.isNotEmpty(scoreRecordsParamList);

        Long courseSelectionId = scoreRecordsParamList.get(0).getCourseSelectionId();
        CourseSelection courseSelection = courseSelectionService.getById(courseSelectionId);
        assert courseSelection != null;

        //remove first.
        remove(new LambdaQueryWrapper<ScoreRecords>()
                .eq(ScoreRecords::getCourseSelectionId, courseSelectionId)
                .eq(ScoreRecords::getCategory, scoreRecordsParamList.get(0).getCategory()));

        //get all score item list.
        List<ScoreItem> scoreItems = scoreItemService.list(new LambdaQueryWrapper<ScoreItem>().eq(ScoreItem::getStatus, 0));
        //then add
        List<ScoreRecords> list = scoreRecordsParamList.stream().filter(item -> item.getItemScore() != null).map(item -> {
            ScoreRecords scoreRecords = new ScoreRecords();
            BeanUtil.copyProperties(item, scoreRecords);
            scoreRecords.setCourseScheduleFrequencyId(courseSelection.getCourseScheduleFrequencyId());
            scoreRecords.setStudentId(courseSelection.getStudentId());
            scoreItems.stream().filter(scoreItem -> scoreItem.getId().equals(item.getItemId())).findAny().ifPresent(scoreItem -> {
                scoreRecords.setItemName(scoreItem.getItemName());
                scoreRecords.setItemFullScore(scoreItem.getFullScore());
            });
            return scoreRecords;
        }).collect(Collectors.toList());
        saveBatch(list);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<ScoreRecordsParam> scoreRecordsParamList) {
        scoreRecordsParamList.forEach(scoreRecordsParam -> {
            this.removeById(scoreRecordsParam.getId());
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(ScoreRecordsParam scoreRecordsParam) {
        ScoreRecords scoreRecords = this.queryScoreRecords(scoreRecordsParam);
        BeanUtil.copyProperties(scoreRecordsParam, scoreRecords);
        this.updateById(scoreRecords);
    }

    @Override
    public ScoreRecords detail(ScoreRecordsParam scoreRecordsParam) {
        return this.queryScoreRecords(scoreRecordsParam);
    }

    /**
     * 获取打分记录
     *
     * @author kongxm
     * @date 2022-07-17 14:52:27
     */
    private ScoreRecords queryScoreRecords(ScoreRecordsParam scoreRecordsParam) {
        ScoreRecords scoreRecords = this.getById(scoreRecordsParam.getId());
        if (ObjectUtil.isNull(scoreRecords)) {
            throw new ServiceException(ScoreRecordsExceptionEnum.NOT_EXIST);
        }
        return scoreRecords;
    }

    @Override
    public void export(ScoreRecordsParam scoreRecordsParam) {
        List<ScoreRecords> list = this.list(scoreRecordsParam);
        PoiUtil.exportExcelWithStream("SnowyScoreRecords.xls", ScoreRecords.class, list);
    }

}
